﻿using AutoMapper;
using BW.MesProject.BasicData.Domain.基础;
using BW.MesProject.BasicData.Infrastructure;
using BW.MesProject.Public.ErrorCode;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using Yitter.IdGenerator;
using OfficeOpenXml;
using System.IO;
using System.Drawing;

namespace BW.MesProject.BasicData.Host.Controllers
{
    /// <summary>
    /// 客户
    /// </summary>
    [Route("api/[controller]/[action]")]
    [ApiController]
    public class ConsumerController : ControllerBase
    {
        private readonly IConsumerServices consumerServices;

        public ConsumerController(IConsumerServices consumerServices)
        {
            this.consumerServices = consumerServices;
        }
        /// <summary>
        /// 添加客户
        /// </summary>
        /// <param name="model">客户模型</param>
        /// <returns>操作结果</returns>
        [HttpPost]
        public ApiResult<int> AddConsumer(Consumermodel model)
        {
            return consumerServices.AddConsumer(model);
        }
        /// <summary>
        /// 删除客户
        /// </summary>
        /// <param name="id">客户ID</param>
        /// <returns>操作结果</returns>
        [HttpPut]
        public ApiResult<int> DeleteConsumer(long id)
        {
            return consumerServices.DeleteConsumer(id);
        }
        /// <summary>
        /// 获取所有客户
        /// </summary>
        /// <returns>客户列表</returns>
        [HttpGet]
        public ApiResult<List<Consumermodel>> GetAllConsumer()
        {
           return consumerServices.GetAllConsumer();
        }
        /// <summary>
        /// 分页获取客户
        /// </summary>
        /// <param name="Consumercode">客户编码</param>
        /// <param name="Consumername">客户名称</param>
        /// <param name="pageindex">页码</param>
        /// <param name="pagesize">每页大小</param>
        /// <returns>分页客户列表</returns>
        [HttpGet]
        public ApiPaging<List<Consumermodel>> GetConsumer(string? Consumercode, string? Consumername, int pageindex, int pagesize)
        {
            return consumerServices.GetConsumer(Consumercode, Consumername, pageindex, pagesize);
        }
        /// <summary>
        /// 根据ID获取客户
        /// </summary>
        /// <param name="id">客户ID</param>
        /// <returns>客户信息</returns>
        [HttpGet]
        public ApiResult<Consumermodel> GetConsumerById(long id)
        {
           return consumerServices.GetConsumerById(id);
        }
        /// <summary>
        /// 更新客户
        /// </summary>
        /// <param name="model">客户模型</param>
        /// <returns>操作结果</returns>
        [HttpPost]
        public ApiResult<int> UpdateConsumer(Consumermodel model)
        {
           return consumerServices.UpdateConsumer(model);
        }
        /// <summary>
        /// 导出客户到Excel
        /// </summary>
        /// <returns>Excel文件</returns>
        [HttpGet]
        public IActionResult ExportConsumerToExcel()
        {
            try
            {
                // 获取所有客户数据
                var result = consumerServices.GetAllConsumer();
                if (result.Code != ApiEnums.Success || result.Data == null)
                {
                    return BadRequest("获取客户数据失败");
                }
                
                // 使用所有数据
                var data = result.Data;
                
                // 创建Excel包
                using (var package = new ExcelPackage())
                {
                    // 添加工作表
                    var worksheet = package.Workbook.Worksheets.Add("客户信息");
                    
                    // 设置表头样式
                    var headerRange = worksheet.Cells[1, 1, 1, 8];
                    headerRange.Style.Font.Bold = true;
                    headerRange.Style.Fill.PatternType = OfficeOpenXml.Style.ExcelFillStyle.Solid;
                    headerRange.Style.Fill.BackgroundColor.SetColor(Color.LightGray);
                    headerRange.Style.Font.Color.SetColor(Color.Black);
                    headerRange.Style.HorizontalAlignment = OfficeOpenXml.Style.ExcelHorizontalAlignment.Center;
                    
                    // 添加表头
                    string[] headers = new string[] 
                    {
                        "客户编码", "客户名称", "简称", "联系方式", 
                        "地址", "客户备注", "社会信用代码", "创建时间"
                    };
                    
                    for (int i = 0; i < headers.Length; i++)
                    {
                        worksheet.Cells[1, i + 1].Value = headers[i];
                    }
                    
                    // 填充数据
                    if (data.Any())
                    {
                        int row = 2;
                        foreach (var item in data)
                        {
                            worksheet.Cells[row, 1].Value = item.Consumercode;
                            worksheet.Cells[row, 2].Value = item.Consumername;
                            worksheet.Cells[row, 3].Value = item.Consumerabbreviation;
                            worksheet.Cells[row, 4].Value = item.Consumerphone;
                            worksheet.Cells[row, 5].Value = item.Consumeradress;
                            worksheet.Cells[row, 6].Value = item.Consumerremarks;
                            worksheet.Cells[row, 7].Value = item.Socialcredit;
                            worksheet.Cells[row, 8].Value = item.CreatedTime;
                            
                            // 设置日期格式
                            if (item.CreatedTime != default)
                            {
                                worksheet.Cells[row, 8].Style.Numberformat.Format = "yyyy-MM-dd HH:mm:ss";
                            }
                            
                            row++;
                        }
                        
                        // 设置数据区域的样式
                        var dataRange = worksheet.Cells[2, 1, row - 1, 8];
                        dataRange.Style.HorizontalAlignment = OfficeOpenXml.Style.ExcelHorizontalAlignment.Left;
                        dataRange.Style.Border.Top.Style = OfficeOpenXml.Style.ExcelBorderStyle.Thin;
                        dataRange.Style.Border.Bottom.Style = OfficeOpenXml.Style.ExcelBorderStyle.Thin;
                        dataRange.Style.Border.Left.Style = OfficeOpenXml.Style.ExcelBorderStyle.Thin;
                        dataRange.Style.Border.Right.Style = OfficeOpenXml.Style.ExcelBorderStyle.Thin;
                    }
                    
                    // 自动调整列宽
                    worksheet.Cells.AutoFitColumns();
                    
                    // 将Excel包转换为字节数组
                    var excelData = package.GetAsByteArray();
                    
                    // 返回Excel文件
                    return File(
                        excelData,
                        "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet",
                        $"客户信息_{DateTime.Now:yyyyMMddHHmmss}.xlsx"
                    );
                }
            }
            catch (Exception ex)
            {
                return BadRequest($"导出Excel失败: {ex.Message}");
            }
        }
    }
}
